package com.jdew.thkj.fragment;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.activity.LoginActivity;
import com.jdew.thkj.activity.MainActivity;
import com.jdew.thkj.activity.MainSearchActivity;
import com.jdew.thkj.activity.SearchActivity;
import com.jdew.thkj.activity.TbProductDetailActivity;
import com.jdew.thkj.adapter.SuperAdapter;
import com.jdew.thkj.base.BaseFragment;
import com.jdew.thkj.bean.SuperSearchBean;
import com.jdew.thkj.listener.AppBarStateChangeListener;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.OnItemClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * 优惠特惠Fragment
 */
public class DiscountsFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.main_tab)
    RadioGroup main_tab;
    @Bind(R.id.price)
    RadioButton price;
    @Bind(R.id.sosuo)
    TextView search;
    @Bind(R.id.swipe_target)
    RecyclerView recycleView;
    @Bind(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @Bind(R.id.iv_1)
    ImageView iv1;
    @Bind(R.id.iv_2)
    ImageView iv2;
    @Bind(R.id.iv_3)
    ImageView iv3;
    @Bind(R.id.iv_4)
    ImageView iv4;
    @Bind(R.id.iv_5)
    ImageView iv5;
    @Bind(R.id.iv_6)
    ImageView iv6;
    @Bind(R.id.iv_7)
    ImageView iv7;
    @Bind(R.id.iv_8)
    ImageView iv8;
    @Bind(R.id.iv_9)
    ImageView iv9;
    @Bind(R.id.iv_10)
    ImageView iv10;
    @Bind(R.id.collapsingToolbar)
    CollapsingToolbarLayout collapsingToolbar;
    @Bind(R.id.appbar)
    AppBarLayout appbar;
    private Boolean paixun = false;
    private SuperAdapter superadapter;
    private int page = 1;
    private String sortType = "tk_total_sales";
    private String keywords = ".";
    private boolean HasCoupon = true;
    private Dialog mWeiboDialog;
    public List<SuperSearchBean.DataBean.TbkDgMaterialOptionalResponseBean.ResultListBean.MapDataBean> list;

    @Override
    protected int getContentViewId() {
        return R.layout.menu_1;
    }

    @Override
    protected void onCreateViewT() {
    }
    public static DiscountsFragment newInstance() {
        DiscountsFragment fragment = new DiscountsFragment();
        return fragment;
    }
    @Override
    public void initData() {
        initView();
        setListener();
        RequestData();
    }


    //获取控件
    private void initView() {
        mActivity = (MainActivity) getActivity();
        sp = mActivity.getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        RadioButton rb = (RadioButton) main_tab.getChildAt(0);
        search.setOnClickListener(this);
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        iv4.setOnClickListener(this);
        iv5.setOnClickListener(this);
        iv6.setOnClickListener(this);
        iv7.setOnClickListener(this);
        iv8.setOnClickListener(this);
        iv9.setOnClickListener(this);
        iv10.setOnClickListener(this);
        rb.setChecked(true);
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        list = new ArrayList<>();
        superadapter = new SuperAdapter(mActivity, list);
        setRcycleview(recycleView, superadapter);
        superadapter.setItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(mActivity, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    String ItemId = list.get(position).getNum_iid() + "";
                    toDetail(ItemId);
                }
            }
        });
        price.setCompoundDrawables(null, null, drawable, null);
        price.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!paixun) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.price_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable, null);
                    sortType = "price_des";
                    paixun = true;
                } else {
                    Drawable drawable = getResources().getDrawable(R.mipmap.price_up);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    price.setCompoundDrawables(null, null, drawable, null);
                    sortType = "price_asc";
                    paixun = false;
                }
                page = 1;
                RequestData();
            }

        });
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(mActivity));
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(mActivity));
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                RequestData();
                smartRefreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                RequestData();
                smartRefreshLayout.finishRefresh();
            }
        });
    }


    //设置监听
    private void setListener() {
        //RadioGroup的事件监听
        main_tab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                for (int index = 0; index < main_tab.getChildCount(); index++) {
                    RadioButton rb = (RadioButton) main_tab.getChildAt(index);
                    if (rb.isChecked()) {
                        gerSelected(index);
                        break;
                    }
                }
                page = 1;
                RequestData();
            }
        });
    }

    public void gerSelected(int i) {
        if (i == 0) {
            sortType = "tk_total_sales";
        } else if (i == 1) {
            sortType = "tk_rate_des";
        } else if (i == 2) {
            if (!paixun) {
                sortType = "price_des";
            } else {
                sortType = "price_asc";
            }
        } else if (i == 3) {
            sortType = "total_sales_des";
        }
        Drawable drawable = getResources().getDrawable(R.mipmap.price_normal);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        price.setCompoundDrawables(null, null, drawable, null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sosuo: {
                startActivity(new Intent(mActivity, MainSearchActivity.class));
            }
            break;
            case R.id.iv_1: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "女装");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_2: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "母婴");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_3: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "家居");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_4: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "男装");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_5: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "鞋包");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_6: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "数码");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_7: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "食品");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_8: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "电器");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_9: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "美妆");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            case R.id.iv_10: {
                Intent in = new Intent(mActivity, SearchActivity.class);
                in.putExtra("result", "配饰");
                mActivity.setResult(1, in);
                startActivity(in);
            }
            break;
            default:
                break;
        }
    }

    public void RequestData() {
        if (!DeviceUtils.isNetworkAvalible(mActivity)) {
            ToastUtils.getInstance(mActivity).showMessage("网络连接错误请检查");
            return;
        }
        if (null != mWeiboDialog) {
            mWeiboDialog.dismiss();
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(mActivity);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).Getlookups(keywords, sortType, page + "", HasCoupon, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "q" + keywords + "sort" + sortType + "PageIndex" + page + "HasCoupon" + HasCoupon)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(JSONObject obj) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (obj.getString("code").equals("0")) {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                    try {
                        SuperSearchBean bean = JSONObject.parseObject(obj.toString(), SuperSearchBean.class);
                        if (null == bean.getData() || null == bean.getData().getTbk_dg_material_optional_response().getResult_list()) {
                            list.clear();
                            superadapter.setDataList(list);
                            return;
                        }
                        if (page == 1) {
                            list.clear();
                        }
                        list.addAll(bean.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data());
                        superadapter.setDataList(list);
                    } catch (Exception e) {
                    }
                }
            }
        });
    }

    public void toDetail(String ItemId) {
        Bundle b = new Bundle();
        b.putSerializable("itemId", ItemId);
        startActivity(TbProductDetailActivity.class, b);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != list) {
            list.clear();
            list = null;
        }
    }
}
